<template>
  <div class="drug-management">
    <div class="page-header">
      <h2>药品管理</h2>
      <button class="add-btn" @click="showAddModal = true">
        <i class="fas fa-plus"></i>
        添加药品
      </button>
    </div>

    <div class="search-bar">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索药品名称..."
        @input="handleSearch"
      >
      <select v-model="categoryFilter" @change="handleSearch">
        <option value="">所有分类</option>
        <option v-for="category in categories" :key="category" :value="category">
          {{ category }}
        </option>
      </select>
    </div>

    <div class="drug-list">
      <table>
        <thead>
          <tr>
            <th>药品名称</th>
            <th>分类</th>
            <th>价格</th>
            <th>库存</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="drug in drugs" :key="drug.id">
            <td>{{ drug.name }}</td>
            <td>{{ drug.category }}</td>
            <td>¥{{ drug.price }}</td>
            <td>{{ drug.stock }}</td>
            <td>
              <span :class="['status', drug.stock > 0 ? 'in-stock' : 'out-of-stock']">
                {{ drug.stock > 0 ? '有货' : '缺货' }}
              </span>
            </td>
            <td class="actions">
              <button class="edit-btn" @click="editDrug(drug)">
                <i class="fas fa-edit"></i>
              </button>
              <button class="delete-btn" @click="confirmDelete(drug)">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑药品模态框 -->
    <div class="modal" v-if="showAddModal || showEditModal">
      <div class="modal-content">
        <h3>{{ showEditModal ? '编辑药品' : '添加药品' }}</h3>
        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label>药品名称</label>
            <input type="text" v-model="currentDrug.name" required>
          </div>
          <div class="form-group">
            <label>分类</label>
            <select v-model="currentDrug.category" required>
              <option v-for="category in categories" :key="category" :value="category">
                {{ category }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>价格</label>
            <input type="number" v-model="currentDrug.price" step="0.01" required>
          </div>
          <div class="form-group">
            <label>库存</label>
            <input type="number" v-model="currentDrug.stock" required>
          </div>
          <div class="form-group">
            <label>描述</label>
            <textarea v-model="currentDrug.description"></textarea>
          </div>
          <div class="form-group">
            <label>图片</label>
            <input type="file" @change="handleImageUpload" accept="image/*">
          </div>
          <div class="modal-actions">
            <button type="button" class="cancel-btn" @click="closeModal">取消</button>
            <button type="submit" class="submit-btn">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-content">
        <h3>确认删除</h3>
        <p>确定要删除药品 "{{ drugToDelete?.name }}" 吗？</p>
        <div class="modal-actions">
          <button class="cancel-btn" @click="showDeleteModal = false">取消</button>
          <button class="delete-btn" @click="deleteDrug">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'DrugManagement',
  setup() {
    const drugs = ref([]);
    const categories = ref(['处方药', '非处方药', '保健品', '医疗器械']);
    const searchQuery = ref('');
    const categoryFilter = ref('');
    const showAddModal = ref(false);
    const showEditModal = ref(false);
    const showDeleteModal = ref(false);
    const currentDrug = ref({
      name: '',
      category: '',
      price: '',
      stock: '',
      description: '',
      image: null
    });
    const drugToDelete = ref(null);

    const fetchDrugs = async () => {
      try {
        console.log('正在请求药品列表...');
        const params = {
          name: searchQuery.value,
          category: categoryFilter.value
        };
        const response = await axios.get('/api/admin/drugs', { params });
        console.log('药品列表请求成功，响应数据:', response.data);
        drugs.value = response.data;
      } catch (error) {
        console.error('获取药品列表失败:', error.response ? error.response.data : error.message);
      }
    };

    const handleSearch = () => {
      fetchDrugs();
    };

    const editDrug = (drug) => {
      currentDrug.value = { ...drug };
      showEditModal.value = true;
    };

    const confirmDelete = (drug) => {
      drugToDelete.value = drug;
      showDeleteModal.value = true;
    };

    const deleteDrug = async () => {
      try {
        await axios.delete(`/api/admin/drugs/${drugToDelete.value.id}`);
        await fetchDrugs();
        showDeleteModal.value = false;
      } catch (error) {
        console.error('删除药品失败:', error);
      }
    };

    const handleSubmit = async () => {
      try {
        const formData = new FormData();
        formData.append('name', currentDrug.value.name);
        formData.append('category', currentDrug.value.category);
        formData.append('price', currentDrug.value.price);
        formData.append('stock', currentDrug.value.stock);
        formData.append('description', currentDrug.value.description);

        if (currentDrug.value.image instanceof File) {
          formData.append('image', currentDrug.value.image);
        } else if (currentDrug.value.image) {
          // 如果是编辑且没有新图片上传，但有原有图片路径，则发送原有路径
          formData.append('image', currentDrug.value.image);
        }

        if (showEditModal.value) {
          await axios.put(`/api/admin/drugs/${currentDrug.value.id}`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
        } else {
          await axios.post('/api/admin/drugs', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
        }
        await fetchDrugs();
        closeModal();
      } catch (error) {
        console.error('保存药品失败:', error);
        alert('保存药品失败，请检查控制台错误信息');
      }
    };

    const handleImageUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        currentDrug.value.image = file;
      }
    };

    const closeModal = () => {
      showAddModal.value = false;
      showEditModal.value = false;
      currentDrug.value = {
        name: '',
        category: '',
        price: '',
        stock: '',
        description: '',
        image: null
      };
    };

    onMounted(() => {
      fetchDrugs();
    });

    return {
      drugs,
      categories,
      searchQuery,
      categoryFilter,
      showAddModal,
      showEditModal,
      showDeleteModal,
      currentDrug,
      drugToDelete,
      handleSearch,
      editDrug,
      confirmDelete,
      deleteDrug,
      handleSubmit,
      handleImageUpload,
      closeModal
    };
  }
};
</script>

<style scoped>
.drug-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  background: #42b983;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-bar input,
.search-bar select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-bar input {
  flex: 1;
}

.drug-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #f8f9fa;
  font-weight: 600;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
}

.status.in-stock {
  background: #d4edda;
  color: #155724;
}

.status.out-of-stock {
  background: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 8px;
}

.edit-btn,
.delete-btn {
  padding: 6px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background: #17a2b8;
  color: white;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.submit-btn {
  background: #42b983;
  color: white;
}
</style> 